package ru.aptu.socket_factory;

import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;

/**
 * Created by IntelliJ IDEA.
 * User: andrey
 * Date: 2/10/12
 * Time: 3:27 PM
 */

public class BillingServerSocketFactory {

    public static class SSLServerSocketCreationException extends Exception {
    }

    public static ServerSocket createServerSocket(int port, InetAddress host) throws IOException {

        String certificate = System.getProperty("javax.net.ssl.keyStore");
        String password = System.getProperty("javax.net.ssl.keyStorePassword");

        try {
            if (certificate == null || certificate.equals("") || password == null || password.equals("") || !(new File(certificate)).isFile()) {
                throw new SSLServerSocketCreationException();
            } else {
                SSLServerSocketFactory socketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
                try {
                    return socketFactory.createServerSocket(port, 1, host);
                } catch (IOException e) {
                    throw new SSLServerSocketCreationException();
                }
            }
        } catch (SSLServerSocketCreationException ex) {
            ServerSocketFactory socketFactory = ServerSocketFactory.getDefault();
            return socketFactory.createServerSocket(port, 1, host);
        }
    }
}
